summaryrefslogtreecommitdiffhomepage
path: root/packages/console/app/src/routes/workspace/[id]/billing/monthly-limit-section.tsx
blob: 7da1de23893b2019bd2dff9b8633936719d9f873 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import { json, action, useParams, createAsync, useSubmission } from "@solidjs/router"
import { createEffect, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { withActor } from "~/context/auth.withActor"
import { Billing } from "@opencode-ai/console-core/billing.js"
import styles from "./monthly-limit-section.module.css"
import { queryBillingInfo } from "../../common"
import { useI18n } from "~/context/i18n"
import { formError, localizeError } from "~/lib/form-error"

const setMonthlyLimit = action(async (form: FormData) => {
  "use server"
  const limit = form.get("limit") as string | null
  if (!limit) return { error: formError.limitRequired }
  const numericLimit = parseInt(limit)
  if (numericLimit < 0) return { error: formError.monthlyLimitInvalid }
  const workspaceID = form.get("workspaceID") as string | null
  if (!workspaceID) return { error: formError.workspaceRequired }
  return json(
    await withActor(
      () =>
        Billing.setMonthlyLimit(numericLimit)
          .then((data) => ({ error: undefined, data }))
          .catch((e) => ({ error: e.message as string })),
      workspaceID,
    ),
    { revalidate: queryBillingInfo.key },
  )
}, "billing.setMonthlyLimit")

export function MonthlyLimitSection() {
  const params = useParams()
  const i18n = useI18n()
  const submission = useSubmission(setMonthlyLimit)
  const [store, setStore] = createStore({ show: false })
  const billingInfo = createAsync(() => queryBillingInfo(params.id!))

  let input: HTMLInputElement

  createEffect(() => {
    if (!submission.pending && submission.result && !submission.result.error) {
      hide()
    }
  })

  function show() {
    // submission.clear() does not clear the result in some cases, ie.
    //  1. Create key with empty name => error shows
    //  2. Put in a key name and creates the key => form hides
    //  3. Click add key button again => form shows with the same error if
    //     submission.clear() is called only once
    while (true) {
      submission.clear()
      if (!submission.result) break
    }
    setStore("show", true)
    input.focus()
  }

  function hide() {
    setStore("show", false)
  }

  return (
    <section class={styles.root}>
      <div data-slot="section-title">
        <h2>{i18n.t("workspace.monthlyLimit.title")}</h2>
        <p>{i18n.t("workspace.monthlyLimit.subtitle")}</p>
      </div>
      <div data-slot="section-content">
        <div data-slot="balance">
          <div data-slot="amount">
            {billingInfo()?.monthlyLimit ? <span data-slot="currency">$</span> : null}
            <span data-slot="value">{billingInfo()?.monthlyLimit ?? "-"}</span>
          </div>
          <Show
            when={!store.show}
            fallback={
              <form action={setMonthlyLimit} method="post" data-slot="create-form">
                <div data-slot="input-container">
                  <input
                    required
                    ref={(r) => (input = r)}
                    data-component="input"
                    name="limit"
                    type="number"
                    placeholder={i18n.t("workspace.monthlyLimit.placeholder")}
                  />
                  <Show when={submission.result && submission.result.error}>
                    {(err) => <div data-slot="form-error">{localizeError(i18n.t, err())}</div>}
                  </Show>
                </div>
                <input type="hidden" name="workspaceID" value={params.id} />
                <div data-slot="form-actions">
                  <button type="reset" data-color="ghost" onClick={() => hide()}>
                    {i18n.t("common.cancel")}
                  </button>
                  <button type="submit" data-color="primary" disabled={submission.pending}>
                    {submission.pending
                      ? i18n.t("workspace.monthlyLimit.setting")
                      : i18n.t("workspace.monthlyLimit.set")}
                  </button>
                </div>
              </form>
            }
          >
            <button data-color="primary" onClick={() => show()}>
              {billingInfo()?.monthlyLimit
                ? i18n.t("workspace.monthlyLimit.edit")
                : i18n.t("workspace.monthlyLimit.set")}
            </button>
          </Show>
        </div>
        <Show
          when={billingInfo()?.monthlyLimit}
          fallback={<p data-slot="usage-status">{i18n.t("workspace.monthlyLimit.noLimit")}</p>}
        >
          <p data-slot="usage-status">
            {i18n.t("workspace.monthlyLimit.currentUsage.beforeMonth")}{" "}
            {new Date().toLocaleDateString(undefined, { month: "long", timeZone: "UTC" })}{" "}
            {i18n.t("workspace.monthlyLimit.currentUsage.beforeAmount")}
            {(() => {
              const dateLastUsed = billingInfo()?.timeMonthlyUsageUpdated
              if (!dateLastUsed) return "0"

              const current = new Date().toLocaleDateString(undefined, {
                year: "numeric",
                month: "long",
                timeZone: "UTC",
              })
              const lastUsed = dateLastUsed.toLocaleDateString(undefined, {
                year: "numeric",
                month: "long",
                timeZone: "UTC",
              })
              if (current !== lastUsed) return "0"
              return ((billingInfo()?.monthlyUsage ?? 0) / 100000000).toFixed(2)
            })()}
            .
          </p>
        </Show>
      </div>
    </section>
  )
}